package com.xbongbong.paas.toolbox.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class CloneUtil {
    private static final Logger LOG = LoggerFactory.getLogger(CloneUtil.class);

	// 用序列化与反序列化实现深克隆
    public static Object deepClone(Object src)
    {
        Object o = null;
        ObjectOutputStream oos = null;
        ObjectInputStream ois = null;
        try {
            if (src != null) {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();

                oos = new ObjectOutputStream(baos);
                oos.writeObject(src);
                ByteArrayInputStream bais = new ByteArrayInputStream(baos
                        .toByteArray());
                ois = new ObjectInputStream(bais);
                o = ois.readObject();
            }
        } catch (IOException e) {
            LOG.error("CloneUtil.deepClone", e);
        } catch (ClassNotFoundException e) {
            LOG.error("CloneUtil.deepClone", e);
        } finally {
            if (oos != null) {
                try {
                    oos.close();
                } catch (IOException e) {
                    LOG.error("CloneUtil.deepClone", e);
                }
            }
            if (ois != null) {
                try {
                    ois.close();
                } catch (IOException e) {
                    LOG.error("CloneUtil.deepClone", e);
                }
            }
        }
        return o;
    }

    // 用序列化与反序列化实现深克隆
    public static <T> T deepClone4Obj(T src) {
        return (T) deepClone(src);
    }
}
